# -*- coding: utf-8 -*-
import json
import logging.config
from datetime import datetime
from logs.config import LOG_SETTINGS

from flask import Flask
from flask import request

from cmd_parser import CmdParser, LOTTERY_TYPE
from send_daily_report import current_report, history_report
from utils import tz
from utils.interface import send_text_msg, send_inline_markup_msg, send_callback_ack
from utils.cache import set_activity_switch, get_activity_switch
from settings import MG as mg


_LOGGER = logging.getLogger('bot')


app = Flask(__name__)

WHITE_GROUP_IDS = [
    2808, # CP数据
]
WHITE_UIDS = [
    8036187, # mik
    8001739, # mik
    8039163, # mik
    20039366, # lis
    8039279, # jam 
    8001463, # kev
]


def start_controle_menu(chat_type, chat_id):
    inline_markup = []
    c = 0
    for k, v in LOTTERY_TYPE.items():
        if c % 4 == 0:
            inline_markup.append({
                "buttons": []
            })
        off = get_activity_switch(k)
        status = u'已开启' if not off else u'已关闭'
        i = inline_markup[-1]["buttons"]
        i.append({
            'text': u'{}-{}'.format(v, status),
            'callback_data': 'cmd_switch_{}'.format(k)
        })
    send_inline_markup_msg(chat_type, chat_id, u'彩种开关状态', inline_markup)


def start_menu(chat_type, chat_id):
    inline_markup = [
        {
            "buttons":[{
                'text': u'今日用户',
                'callback_data': 'cmd_today_user'
            },{
                'text': u'今日流水',
                'callback_data': 'cmd_today_recharge'
            },{
                'text': u'今日营收',
                'callback_data': 'cmd_today_profit'
            }],
        },{
            "buttons":[{
                'text': u'今日购彩',
                'callback_data': 'cmd_today_bigbang'
            }],
        },{
            "buttons":[{
                'text': u'百人牛牛',
                'callback_data': 'cmd_today_bull'
            },{
                'text': u'大转盘',
                'callback_data': 'cmd_today_lottery'
            },{
                'text': u'slots',
                'callback_data': 'cmd_today_slots'
            },{
                'text': u'猜水果',
                'callback_data': 'cmd_today_fruit'
            }]
        }
    ]
    send_inline_markup_msg(chat_type, chat_id, u'今日数据', inline_markup)


def start_menu_yesterday(chat_type, chat_id):
    inline_markup = [
        {
            "buttons":[{
                'text': u'昨日用户',
                'callback_data': 'cmd_yesterday_user'
            },{
                'text': u'昨日流水',
                'callback_data': 'cmd_yesterday_recharge'
            },{
                'text': u'昨日营收',
                'callback_data': 'cmd_yesterday_profit'
            }],
        },{
            "buttons":[{
                'text': u'今日购彩',
                'callback_data': 'cmd_yesterday_bigbang'
            }],
        },{
            "buttons":[{
                'text': u'百人牛牛',
                'callback_data': 'cmd_yesterday_bull'
            },{
                'text': u'大转盘',
                'callback_data': 'cmd_yesterday_lottery'
            },{
                'text': u'slots',
                'callback_data': 'cmd_yesterday_slots'
            },{
                'text': u'猜水果',
                'callback_data': 'cmd_yesterday_fruit'
            }]
        }
    ]
    send_inline_markup_msg(chat_type, chat_id, u'昨日数据', inline_markup)


def query_report(cmd):
    date_str = cmd[7:]
    try:
        date = datetime.strptime(date_str, '%Y%m%d')
        now_date = datetime.strptime(tz.local_now().strftime('%Y%m%d'), '%Y%m%d')
        delta = (now_date - date).days
        return history_report(delta)
    except Exception as e:
        _LOGGER.exception('query_report, error %s', e)
        return current_report()
    

@app.route("/hook", methods=['GET', 'POST'])
def hook():
    msg = json.loads(request.data)
    _LOGGER.info(u'%s', msg)
    msg = msg[0]
    if 'callback_query' in msg:
        r_type = 2 # inline msg
        res = msg['callback_query']
        (uid, first_name, msg_id, chat_data, inline_message_id) = (
            res['from'].get('id'), res['from'].get('first_name'),
            res['message_id'], res['data'], res['inline_message_id']
        )
        chat_type, chat_id = 1, uid
    else:
        r_type = 1
        res = msg['message']
        (uid, first_name, chat_type, chat_id, msg_id, chat_text) = (
            res['from'].get('id'), res['from'].get('first_name'),
            res['chat'].get('type'), res['chat'].get('id'),
            res.get('message_id'), res.get('text'))
    parser = CmdParser()
    if r_type == 1:
        text = chat_text
        if text == '/start' or text == '/today':
            start_menu(chat_type, chat_id)
        elif text == '/yesterday':
            start_menu_yesterday(chat_type, chat_id)
        elif text == '/control308227' and uid in WHITE_UIDS:
            start_controle_menu(chat_type, chat_id)
        elif text.startswith('/report'):
            if (uid in WHITE_UIDS or (chat_type == 3 and chat_id in WHITE_GROUP_IDS)):
                resp_msg = query_report(text)
                if resp_msg:
                    send_text_msg(chat_type, chat_id, resp_msg)
                    return 'ok'
            else:
                send_text_msg(chat_type, chat_id, u'请联系管理员开通权限')
                return 'ok'
        elif chat_type == 1:
            match_cmd = parser.match_text(text)
            if match_cmd:
                if (uid in WHITE_UIDS or (chat_type == 3 and chat_id in WHITE_GROUP_IDS)):
                    resp_msg = parser.cmd_resp(match_cmd)
                    if resp_msg:
                        send_text_msg(chat_type, chat_id, resp_msg)
                        return 'ok'
                else:
                    send_text_msg(chat_type, chat_id, u'请联系管理员开通权限')
                    return 'ok'
            start_menu(chat_type, chat_id)
    if r_type == 2 and uid in WHITE_UIDS:
        cmd = chat_data
        resp_msg = parser.cmd_resp(cmd)
        if resp_msg:
            send_text_msg(chat_type, chat_id, resp_msg)
            send_callback_ack(uid, inline_message_id)
            return 'ok'
    return 'fail'


if __name__ == "__main__":
    logging.config.dictConfig(LOG_SETTINGS)
    app.run(host='0.0.0.0')
